% check https://github.com/kth-competitive-programming/kactl/blob/main/content/tex/kactlpkg.sty for updates
% This file contains LaTeX macros for KACTL
% License: CC0
\ProvidesPackage{kactlpkg}

\usepackage{comment}
\usepackage[utf8]{inputenc}             % Encoding UTF-8
\usepackage{listings}                   % Source code listings
\usepackage{framed}                     % Source code listings
\usepackage[a4paper,landscape,hmargin={0.5cm,0.5cm},vmargin={1.0cm,0.4cm}]{geometry}
\usepackage{multicol}                   % Split page in multiple columns
\usepackage{fancyhdr}                   % Fancy headers
\usepackage{amsbsy, amssymb, amsmath}   % Enable math symbols
\usepackage{tocloft}                    % Custom Table of Contents
\usepackage{titletoc}                   % Design control over Table of Contents
\usepackage{ifthen}                     % To enable some conditional programming in LaTeX
\usepackage{courier}                    % To get bold typewriter typeface
\usepackage{graphicx}                   % To rotate page numbers
\usepackage{fix-cm}                     % Large font sizes
\usepackage{paralist}                   % For compact enumerations
\usepackage[inline]{enumitem}           % For horizontal lists
\usepackage[parfill]{parskip}           % For compact enumerations
\usepackage[dvipsnames]{xcolor}         % extra colors
\usepackage[normalem]{ulem}
\usepackage[hidelinks]{hyperref}        % For clickable table of contents

% Config commands
\newcommand{\subtitle}[1]{
	\def\@subtitle{#1}
}
\newcommand{\team}[2]{
	\def\@teamname{#1}
	\def\@teammembers{#2}
}
\newcommand{\contest}[2]{
	\def\@contestname{#1}
	\def\@contestdate{#2}
}
\newcommand{\university}[3]{
	\def\@unishort{#1}
	\def\@unilong{#2}
	\def\@unilogo{#3}
}

\newcommand{\enablecolors}{
	\lstset{basicstyle=\footnotesize\ttfamily\color{mygreen}}
	\lstset{commentstyle=\color{darkgray}\itshape}
	\lstset{keywordstyle=\color{myblue}}
	\lstset{identifierstyle=\color{black}}
}

% Some default config
\subtitle{{\tiny new}KACTL}
\title{KTH Algorithm Competition Template Library}
\newcommand{\PDFColor}{0}
\def\@builddir{build}

\def\today{\number\year-\ifthenelse{\number\month<10}{0}{}\number\month-\ifthenelse{\number\day<10}{0}{}\number\day} % Defines \today as YYYY-MM-DD

\renewcommand{\maketitle}[2]{
	\begin{center}
		{\Huge \@title}\\
		{\huge \@subtitle{} version #2}\\[0.1cm]
		{\Huge \textsc{#1}}
	\end{center}
}

% Remove temp files from old failed runs
\AtBeginDocument{\immediate\write18{rm -f \@builddir/header.tmp}}
\AtEndDocument{\immediate\write18{rm -f \@builddir/header.tmp}\immediate\write18{rm -f \@builddir/header2.tmp}\immediate\write18{rm -f \@builddir/kactl.tmp}}

% https://tex.stackexchange.com/questions/20444/what-are-immediate-write18-and-how-does-one-use-them

% Include a list of source files at the top of every page. For the purpose
% of recording those, we use eTeX marks. (We can't just append data directly to
% the header, because TeX outputs pages asynchronously, noticably so when
% multicol is in use.) There is no command for getting all marks set on a page,
% so we take only the last one and include all non-included files up until that
% one. Most of the time \splitbotmark will give us the right mark, but in rare
% cases things fall down and we try to make the best of things by falling back
% to \botmark. Also, since LaTeX is terrible at string manipulation, we do all
% actual processing in Python, stashing global state in header.tmp.
\newmarks\hdrmark
\pagestyle{fancy}
\renewcommand{\headrulewidth}{0pt}
\headheight 25pt
\lhead{\@unishort}
\chead{\immediate\write18{python2 content/tex/preprocessor.py --print-header "\splitbotmarks\hdrmark|\botmarks\hdrmark" -o \@builddir/header2.tmp}\immediate\input{\@builddir/header2.tmp}}
\rhead{\thepage}
%\lhead{}\chead{\thepage}\rhead{}
\lfoot{}\cfoot{}\rfoot{}
\fancyheadoffset{0pt}
\fancyfootoffset{0pt}
\setlength\headsep{5pt}

\renewcommand\chapter{
	\global\@topnum\z@
	\secdef
	\@chapter
	\@schapter
}

% Don't add appendices to the Table of Contents
% Currently, this disables parts of the local TOC for appendices chapters
\newboolean{appendixmode}
\setboolean{appendixmode}{false}
\let\Oldaddtoc\addcontentsline
\renewcommand{\addcontentsline}[3]{
	\ifthenelse{
		\boolean{appendixmode}\and\equal{#1}{toc}
	}{}{\Oldaddtoc{#1}{#2}{#3}}
}

% Redefine appendix
\renewcommand\appendix{
	% Change chapter counter to A,B,C,...
	\setcounter{tocdepth}{8}
	\setcounter{chapter}{0}
	\def\thechapter{\Alph{chapter}}
	% Switch to appendixmode defined above (disables TOC entries)
	\setboolean{appendixmode}{true}
	\clearpage
}

\def\@makechapterhead#1{
	\parindent \z@ \raggedright \normalfont
		\interlinepenalty\@M
	{\underline{\huge \bfseries #1} }
	\ifnum \c@secnumdepth >\m@ne
		{\huge\bfseries (\thechapter) \par\nobreak }
	\fi
	\startcontents[chapters]
}
\renewcommand\section{\@startsection {section}{1}{\z@}%
                                   {-0.5ex \@plus -1ex \@minus -.2ex}%
                                   {.4ex}%
                                   {\normalfont\LARGE\bfseries}}
\renewcommand\subsection{\@startsection{subsection}{2}{\z@}
	{1ex\@plus -1ex \@minus -.3ex}
	{.2ex}
	{\normalfont\large\bfseries}}
\renewcommand\subsubsection{\@startsection{subsubsection}{3}{\z@}
	{1ex\@plus -1ex \@minus -.3ex}
	{1ex \@plus .2ex}
	{\normalfont\large\bfseries}}
% Styles for local toc
\titlecontents{localsection}[1.5em]{\small}{}
	{\small}{\titlerule*[0.8em]{.}\contentspage}
\titlecontents{localsubsection}[3.8em]{\small}{}
	{\small}{\titlerule*[0.8em]{.}\contentspage}
% Styles for main toc
\renewcommand{\chaptermark}[1]{\markboth{\emph{ #1}}{}}
\renewcommand{\cftbeforetoctitleskip}{-45pt}
\renewcommand{\cftaftertoctitleskip}{10pt}
\renewcommand{\cftbeforechapskip}{11pt}
\renewcommand\cftchapfont{\large\bfseries}
\renewcommand{\cftdotsep}{4.5}

% Proper carets and tildes
\newcommand*{\caret}{%
  \begingroup
    \fontencoding{T1}%
    \fontfamily{pcr}% Courier
    \selectfont
    \string^%
  \endgroup
}
\renewcommand*{\tilde}{\raise.17ex\hbox{$\scriptstyle\mathtt{\sim}$}}

% Fatter {} which are more distinguishable from ()
% Makes pdf compile time 5-10% slower, but probably worth it still?
\newcommand*{\nicelbrace}{%
  \begingroup
    \fontencoding{T1}%
    \fontfamily{pcr}% Courier
    \selectfont
	\scalebox{1.5}[1]{\color{black!80}{\{}}%
  \endgroup
}
\newcommand*{\nicerbrace}{%
  \begingroup
    \fontencoding{T1}%
    \fontfamily{pcr}% Courier
    \selectfont
	\scalebox{1.5}[1]{\color{black!80}{\}}}%
  \endgroup
}

\definecolor{mygreen}{HTML}{007000}
\definecolor{myblue}{HTML}{0000dd}

% Configure source code listings
\lstset{language=C++}
\lstset{morekeywords={alignas,alignof}}
\lstset{deletedirectives={line}}
\lstset{frame=t} % line on top of code block
\lstset{tabsize=2}
\lstset{showstringspaces=false}
\lstset{breaklines=true,breakindent=12pt} 
\lstset{postbreak=\raisebox{0ex}[0ex][0ex]{\color{darkgray}\ensuremath{\hookrightarrow}}} % arrow after break
\lstset{stepnumber=1}
\lstset{numberstyle=\footnotesize\color{black}}


%%% TEXT
% https://tex.stackexchange.com/questions/24599/what-point-pt-font-size-are-large-etc
% tt family: monospaced typedwriter - https://www.tug.org/pracjourn/2006-1/schmidt/schmidt.pdf
% http://texdoc.net/texmf-dist/doc/latex/listings/listings.pdf

% https://tex.stackexchange.com/questions/240262/digit-zero-with-a-dot-inside-also-in-text-mode
% \makeatletter
\DeclareRobustCommand*{\pmzerodot}{%
  \nfss@text{%
    \sbox0{$\vcenter{}$}% math axis
    \sbox2{0}%
    \sbox4{0\/}%
    \ooalign{%
      0\cr
      \hidewidth
      \kern\dimexpr\wd4-\wd2\relax % compensate for slanted fonts
      \raise\dimexpr(\ht2-\dp2)/2-\ht0\relax\hbox{%
        \if b\expandafter\@car\f@series\@nil\relax
          \mathversion{bold}%
        \fi
        $\cdot\m@th$%
      }%
      \hidewidth
      \cr
      \vphantom{0}% correct depth of final symbol
    }%
  }%
}

\newcommand*{\dotarabic}[1]{%
  \expandafter\@dotarabic\csname c@#1\endcsname
}
\newcommand*{\@dotarabic}[1]{%
  \expandafter\dotarabic@scan\number #1\relax
}
\newcommand*{\dotarabic@scan}[1]{%
  \ifx\relax#1%
    \expandafter\@gobble
  \else
    \expandafter\@firstofone
  \fi
  {%
    \ifnum#1=0 %
      \ifincsname
        0%
      \else
        \pmzerodot
      \fi
    \else
      #1%
    \fi
    \dotarabic@scan
  }%
}
% \makeatother

\lstset{basicstyle=\footnotesize\ttfamily}
\lstset{literate={^}{\caret}{1} {~}{\tilde}{1} {\{}{\nicelbrace}{1} {\}}{\nicerbrace}{1} {0}{\pmzerodot}{1}}
\lstset{emptylines=*1}
\lstset{inputencoding=utf8}
\lstset{aboveskip=3pt}
\lstset{belowskip=2pt}

\lstdefinelanguage{raw}{} % Raw language, no keywords.

\setlength{\columnseprule}{0.5pt} % Multicol separation line with
\setlength{\columnsep}{10pt} % Multicol separation margin
\setcounter{tocdepth}{1} % Table of contents depth

\pdfsuppresswarningpagegroup=1

\newcommand{\maketeampage}{
	\pagestyle{empty}
	\setcounter{page}{0}
	\begin{center}
		\strut % Magic
		\vspace{3cm}\\
		\includegraphics[width=3cm]{\@unilogo}\\
		{\fontsize{25}{30}\selectfont \@unilong\\}
		{\fontsize{60}{60}\selectfont \@teamname\\}
		\vspace{0.5cm}
		{\huge \@teammembers\\}
		\vfill
		{\fontsize{21}{25}\selectfont \@contestname}\\
		\vspace{0.5cm}
		{\huge \@contestdate}\\
		\vspace{1cm}
	\end{center}
	\clearpage
	\pagestyle{fancy}
}

\newcommand{\kactlref}[1]{
	\ifthenelse{\boolean{appendixmode}}{}{
		\ifnum \value{section} > 0
			\addcontentsline{ptc}{subsection}{\texttt{#1}\hspace{0.2em}}
		\else
			\addcontentsline{ptc}{section}{\texttt{#1}\hspace{0.2em}}
		\fi
	}
	\marks\hdrmark{#1}
}

% Like \needspace, except with flush bottoms.
\newcommand{\myneedspace}[1]{%
  \begingroup
    \setlength{\dimen@}{#1}%
    \vskip\dimen@
    \penalty 9999%
    \vskip -\dimen@
    \vskip\z@skip
  \endgroup
}

\newcommand{\kactlimport}[2][]{ % Using empty default parameter
	\leftcaption{}\rightcaption{}
	\setboolean{hasdescription}{false}
	\setboolean{hasusage}{false}
	\setboolean{hastime}{false}
	\setboolean{hasmemory}{false}
	\setboolean{hasleftcaption}{false}
	\myneedspace{3\baselineskip}
	\penalty-100
	\immediate\write18{rm -f \@builddir/kactl.tmp} % Don't include old kactl.tmp on failure.
	\immediate\write18{python2 content/tex/preprocessor.py -i "\@kactldir/#2" -o \@builddir/kactl.tmp #1}
	\immediate\input{\@builddir/kactl.tmp}
}

\newcommand{\import}[1]{
	\input{"\@kactldir/#1"}
}

\newcommand{\kactlcontentdir}[1]{
	\def\@kactlbasedir{#1}
	\def\@kactldir{#1}
}
\kactlcontentdir{.}

\newcommand{\kactlchapter}[1]{
	\def\@kactldir{\@kactlbasedir/#1}
	\input{"\@kactldir/chapter.tex"}
	\def\@kactldir{\@kactlbasedir}
}

\newcommand{\kactlerror}[1]{
	\PackageError{kactlpkg}{#1}{}
}

\newcommand{\kactlwarning}[1]{
	\PackageWarning{kactlpkg}{#1}
}

\newboolean{hasleftcaption}
\newcommand{\leftcaption}[1]{
	\def\@leftcaption{#1}
	\setboolean{hasleftcaption}{true}
}
\leftcaption{}
\setboolean{hasleftcaption}{false}

\newcommand{\rightcaption}[1]{
	\def\@rightcaption{#1}
}
\rightcaption{}

\newboolean{hasdescription}
\newcommand{\defdescription}[1]{
	\def\@defdescription{#1}
	\setboolean{hasdescription}{true}
}
\defdescription{}
\setboolean{hasdescription}{false}

\newboolean{hasusage}
\newcommand{\defusage}[1]{
	\def\@defusage{\texttt{#1}}
	\setboolean{hasusage}{true}
}
\defusage{}
\setboolean{hasusage}{false}

\newboolean{hastime}
\newcommand{\deftime}[1]{
	\def\@deftime{#1}
	\setboolean{hastime}{true}
}
\deftime{}
\setboolean{hastime}{false}

\newboolean{hasmemory}
\newcommand{\defmemory}[1]{
	\def\@defmemory{#1}
	\setboolean{hasmemory}{true}
}
\defmemory{}
\setboolean{hasmemory}{false}


\newcommand{\codeheader}[2]{
	{\par\noindent\footnotesize{\textbf{#1:} #2\par}}
}

\long\def\@makecaption#1#2{
	\vspace{-3pt}
	\ifthenelse{\boolean{hasdescription}}{\codeheader{Description}{\@defdescription}}{}
	\ifthenelse{\boolean{hasusage}}{\codeheader{Usage}{\@defusage}}{}
	\ifthenelse{\boolean{hasmemory}}{\codeheader{Memory}{\@defmemory}}{}
	\ifthenelse{\boolean{hastime}}{\codeheader{Time}{\@deftime}}{}
	\ifthenelse{\boolean{hasleftcaption}}{\vspace{0pt}}{\vspace{-5pt}}
	\tiny
	\texttt{\@leftcaption} \hfill \@rightcaption
}

\newcommand{\bigo}[1] {\ensuremath{\mathcal{O} \left( #1 \right)}}

\newcommand{\hardcolumnbreak}{\vfill\null\columnbreak}